/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
 package net.bioteam.appweb.gwt.apps.server.program;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import net.bioteam.appweb.Config;
import net.bioteam.appweb.gwt.apps.clientandserver.Constant;
import net.bioteam.appweb.gwt.apps.clientandserver.program.AppNode;
import net.bioteam.appweb.gwt.apps.clientandserver.program.AppTreeProxy;
import net.bioteam.appweb.gwt.apps.server.MyRemoteServiceServlet;
import net.bioteam.appweb.model.AppDescription;
import net.bioteam.appweb.model.ProgramBuilder;
import net.bioteam.appweb.model.ProgramCategory;
import net.bioteam.appweb.model.ProgramTemplate;
import net.bioteam.appweb.model.ProgramTemplateUtil;
import net.bioteam.common.user.User;
import net.bioteam.common.utils.MyEntityManager;
import edu.emory.mathcs.backport.java.util.Arrays;

public class AppTreeProxyImpl extends MyRemoteServiceServlet implements AppTreeProxy {

	public List<AppNode> getNodes(String parentPath) throws Exception
	{
		List<AppNode> nodes=new LinkedList<AppNode>();
		if (parentPath.startsWith("/"))
			parentPath=parentPath.substring(1);
		String nodeIDs[]=parentPath.split("/");
		HttpServletRequest req = getThreadLocalRequest();
		if (nodeIDs[0].equals("globaltemplates") && nodeIDs.length==1)
		{
			File savedDir = new File(Config.topdir + File.separator + Config.TEMPLATE_DIR + File.separator + Config.PUBLIC_FILE_DIR );
			if (!savedDir.exists())
			{
				savedDir.mkdir();
			}
			for (File file : savedDir.listFiles())
			{
				AppNode node=new AppNode();
				int index = file.getName().indexOf('_');
				node.text=file.getName().substring(index + 1);
				node.leaf=true;
				node.ptype=Constant.global_template_ptype;
				node.pvalue=file.getName();
				node.tip=file.getName().substring(index + 1);
				nodes.add(node);

			}
			return nodes;
		} else if (nodeIDs[0].equals("usertemplate") && nodeIDs.length==1)
		{
			User user=(User)req.getSession().getAttribute("user");
			EntityManager em = MyEntityManager.getEntityManager();
			EntityTransaction tx = em.getTransaction();
			List<ProgramTemplate> runs;
			try {
				tx.begin();
				Query query = em.createNamedQuery("savedruns");
				query.setParameter("username", user.getIdAsString());
				List lists = query.getResultList();
				File savedDir = new File(Config.topdir + File.separator
						+ Config.TEMPLATE_DIR + File.separator + user.getName());
				if (!savedDir.exists()) {
					savedDir.mkdirs();
				}

				runs = new ArrayList<ProgramTemplate>();
				for (Object obj : lists) {
					ProgramTemplate run = (ProgramTemplate) obj;
					File file = new File(savedDir.getAbsolutePath()
							+ File.separator + ProgramTemplateUtil.getFilename(run));
					if (file.exists()) {
						runs.add(run);
					} else {
						em.remove(run);
					}
				}
				tx.commit();
				
				for (ProgramTemplate run : runs) {
					AppNode node=new AppNode();
					
					node.text=run.getName();
					node.leaf= true;
					node.ptype=Constant.user_template_ptype;
					node.pvalue=String.valueOf(run.getId());
					node.tip=run.getDescription();
					nodes.add(node);
				}
				return nodes;
			} catch (RuntimeException e) {
				tx.rollback();
				throw new Exception(e.getMessage());
			}
		} else if (nodeIDs[0].equals("applications"))
		{
			ProgramCategory pc=ProgramBuilder.getProgramCategory();
			List<String> names=Arrays.asList(nodeIDs);
			ProgramCategory childPc=null;
			if (nodeIDs.length==1)
			{
				childPc=pc;
			} else
			{
				childPc=pc.getRecursiveCategory(names.subList(1, names.size()));
			}
			for(ProgramCategory tempPc:childPc.getSubCategories())
			{
				AppNode node=new AppNode();
				node.leaf=false;
				node.text=tempPc.getName();
				node.tip=tempPc.getName();
				nodes.add(node);
			}
			for (AppDescription app: childPc.getApps())
			{
				AppNode node=new AppNode();
				node.leaf=true;
				node.text=app.getProgramName();		
				node.ptype=Constant.program_ptype;
				node.pvalue=app.getProgramName();
				node.tip=app.getTooltip();
				nodes.add(node);
			}
			return nodes;
		}
		return nodes;
	}
	

}
